package com.xzc.algorithm.data_structure_ke.LinkedList;

import lombok.Data;

@Data
public class LinkList<T> {

    @Data
    private static class Node<T> {
        private T t;
        private Node next;

        public Node(T t, Node next) {
            this.t = t;
            this.next = next;
        }

        public Node(T t) {
            this.t = t;
            this.next = null;
        }
    }

    private Node<T> head;
    private int size = 0;

    public int getSize() {
        return size;
    }

    public boolean isEmpty() {
        return size == 0;
    }

    public void add(int index, T t) throws Exception {
        if (index < 0)
            throw new Exception("index必须大于等于0");
        if (head == null && index > 0)
            throw new Exception("siz==0，index>0，不对头");
        if (head == null && index == 0) {
            head = new Node<T>(t);
            size++;
            return;
        }
        if (index == 0) {
            Node<T> tmp = new Node<T>(t);
            tmp.next = head;
            head = tmp;
        } else {
            Node tmp = head;
            for (int i = 0; i < index - 1; i++) {
                tmp = tmp.next;
            }
            tmp.next = new Node(t, tmp.next);
        }
        size++;
    }

    public void addFirst(T t) throws Exception {
        add(0, t);
    }

    public void addLast(T t) throws Exception {
        add(size, t);
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        Node tmp = head;
        for (int i = 0; i < size; i++) {
            sb.append(tmp.t).append(",");
            tmp = tmp.next;
        }
        sb.append("]");
        sb.append(" size=").append(size);
        return sb.toString();
    }
}
